package com.sealer.pattern.behavioral.interpreter;

import java.util.Stack;

/**
 * Created by sealer on 17/04/10.
 */
public class Evaluator implements Expression {
    private Expression expressionTree;

    public Evaluator(String expression) {
        final Stack<Expression> expressionStack = new Stack<>();
        for (String token : expression.split(" ")) {
            if ("+".equals(token)) {
                Expression rightExpr = expressionStack.pop();
                Expression leftExpr = expressionStack.pop();
                Expression subExpression = new Plus(leftExpr, rightExpr);
                expressionStack.push(subExpression);
            } else if ("-".equals(token)) {
                Expression rightExpr = expressionStack.pop();
                Expression leftExpr = expressionStack.pop();
                Expression subExpression = new Minus(leftExpr, rightExpr);
                expressionStack.push(subExpression);
            } else {
                expressionStack.push(new Variable(token));
            }
        }

        expressionTree = expressionStack.pop();
    }

    @Override
    public int interpret(Context context) {
        return expressionTree.interpret(context);
    }
}
